    //
    //  BindDeviceController.swift
    //  flowerpot
    //
    //  Created by fyname on 15/9/18.
    //  Copyright © 2015年 senhe. All rights reserved.
    //
    
    import UIKit
    
    import AVFoundation
    
    class BindDeviceController: UIViewController ,AVCaptureMetadataOutputObjectsDelegate{
        
        //指定的设备是摄像头
        var device:AVCaptureDevice?
        //视频扑捉会话
        var session:AVCaptureSession?
        //视频画面预览层
        var layer: AVCaptureVideoPreviewLayer?
        var line_tag:Int = 1872637
        //var imageViewScan:UIImageView?
        
        override func viewDidLoad() {
            super.viewDidLoad()
            if(device == nil){
                device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
            }
            
            if(session == nil){
                session = AVCaptureSession()
            }
            
            
            // 扫描框布局
            self.title = "绑定设备"
            self.view.backgroundColor = UIColor.grayColor()
            let labIntroudction = UILabel(frame:CGRectMake(15, 80, 290, 50))
            labIntroudction.backgroundColor = UIColor.clearColor()
            labIntroudction.numberOfLines = 2
            labIntroudction.textColor = UIColor.whiteColor()
            labIntroudction.text = "将二维码图像置于矩形方框内，离手机摄像头10CM左右，系统会自动识别。"
            self.view.addSubview(labIntroudction)
            let imageViewBg = UIImageView(frame:CGRectMake(10, 140, 300, 300))
            imageViewBg.image = UIImage(named:"pick_bg")
            self.view.addSubview(imageViewBg)
            let imageViewScan = UIImageView(frame:CGRectMake(10, 150, 300, 2))
            imageViewScan.tag = line_tag
            //imageViewScan.contentMode = UIViewContentModeScaleAspectFill
            imageViewScan.backgroundColor = UIColor.clearColor()
            imageViewScan.image = UIImage(named:"scan")
            
            self.view.addSubview(imageViewScan)
            
            /* 添加动画 */
            /*UIView.animateWithDuration(2.5, delay: 0.0, options: .CurveEaseOut, animations: {
                imageViewScan = CGPoint(x: 75, y: 200)
                }, completion: nil)*/

            
            //添加导航
            let toolBar = UIToolbar()
            toolBar.barStyle = UIBarStyle.Default
            let item0 = UIBarButtonItem(image:(UIImage(named:"ocrBack.png")), style:(UIBarButtonItemStyle.Plain), target:self, action:(Selector("backClick")))
            let item1 = UIBarButtonItem(image:(UIImage(named:"ocr_flash-off.png")), style:(UIBarButtonItemStyle.Plain), target:self, action:(Selector("turnTorchOn")))
            let item2 = UIBarButtonItem(image:(UIImage(named:"ocr_albums.png")), style:(UIBarButtonItemStyle.Plain), target:self, action:(Selector("pickPicture")))
            let flexibleSpaceItem = UIBarButtonItem(barButtonSystemItem : (UIBarButtonSystemItem.FlexibleSpace), target: self, action: nil)
            toolBar.items = [item0,flexibleSpaceItem,item2,flexibleSpaceItem, item1]
            toolBar.frame = CGRectMake(0, UIScreen.mainScreen().bounds.size.height-44, 320, 44)
            self.view.addSubview(toolBar)
        }
        
        
        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
            self.setupCamera()
            self.session!.startRunning()
            self.addAnimation()
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
            
        }
        
        //启动摄像头
        func setupCamera(){
            
            self.session!.sessionPreset = AVCaptureSessionPresetHigh
            if device == nil{
                SweetAlert().showAlert("未发现摄像头设备!", subTitle: "提醒!", style: AlertStyle.Success)
                return
            }
            
            //输入
            if let input = try?AVCaptureDeviceInput(device: device!){
                self.session!.addInput(input)
            }else{
                SweetAlert().showAlert("请在iPhone的\"设置-隐私-相机\"选项中,允许本程序访问您的相机!", subTitle: "提醒!", style: AlertStyle.Success)
                return
            }
            
            //视频预览层与视频扑捉会话关联
            layer = AVCaptureVideoPreviewLayer(session: session)
            layer!.videoGravity = AVLayerVideoGravityResizeAspectFill
            layer!.frame = CGRectMake(20,150,280,280);
            self.view.layer.insertSublayer(self.layer!, atIndex: 0)
            let output = AVCaptureMetadataOutput()
            output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
            if self.session!.canAddOutput(output) {
                self.session!.addOutput(output)
                output.metadataObjectTypes = [AVMetadataObjectTypeQRCode];
            }
            self.session!.startRunning()
        }
        
        //一旦视频扑捉有输出
        func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
            var stringValue:String?
            if metadataObjects.count > 0 {
                let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
                stringValue = metadataObject.stringValue
            }
            self.session!.stopRunning()
            
            SweetAlert().showAlert("二维码", subTitle: "扫到的二维码内容为:\(stringValue)", style: AlertStyle.Success)
        }
        
        /*override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
           
            if((object?.isKindOfClass(AVCaptureSession)) != nil){
                
                //let isRunning:Bool = (AVCaptureSession)object!.running
                //session?.running
                if((session?.running) != nil){
                    addAnimation()
                }else{
                    delAnimation()
                }
            }
        }*/
        
        func addAnimation(){
            log.debug("扫描移动开始!")
            let line:UIView = self.view.viewWithTag(line_tag)!
            line.hidden = false
            //var animation:CABasicAnimation = [BindDeviceController moveYTime:2 fromY:[NSNumber numberWithFloat:0] toY:[NSNumber numberWithFloat:ScreenWidth-60-2] rep:OPEN_MAX];
            let animation:CABasicAnimation = moveYTime(2.0,fromY: 150,toY: 430,rep: 300)
            line.layer.addAnimation(animation, forKey: "LineAnimation")
            log.debug("扫描移动结束!")
        }
        
        func delAnimation(){
            log.debug("移除动画开始!")
            let line:UIView = self.view.viewWithTag(line_tag)!
            line.layer.removeAnimationForKey("LineAnimation")
            line.hidden = true
            log.debug("移除动画结束!")
        }
        
        //.y的话就向下移动。
        func moveYTime(time:Double,fromY:NSNumber,toY:NSNumber,rep:Float)->CABasicAnimation{
            log.debug("接收参数: time:\(time),fromY:\(fromY),toY:\(toY),rep:\(rep)")
            //let animationMove:CABasicAnimation = [CABasicAnimation animationWithKeyPath:;@"transform.translation.y"];
            let animationMove = CABasicAnimation()
            
            animationMove.keyPath = "position.y"
            animationMove.fromValue = fromY
            animationMove.toValue = toY
            animationMove.duration = time
            animationMove.delegate = self
            animationMove.repeatCount  = rep
            animationMove.fillMode = kCAFillModeForwards
            animationMove.removedOnCompletion = false
            //animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]
            animationMove.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
            return animationMove
        }
        
    }
